package com.yiyuan.weixin.utils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.yiyuan.weixin.Common.GlobalConstant;
import com.yiyuan.weixin.model.*;
import com.yiyuan.weixin.weixinInservice.format.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2017/3/24.
 */

public class JsonParseUtil {
    private static <E> E jsonParseService(String json, Object object) {
        if (json == null | json.equals(""))
            return null;
        Gson gson = new Gson();
        try {

            gson.fromJson(json, object.getClass());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return null;
        }
        return (E) gson.fromJson(json, object.getClass());
    }

    private static <E> E getObjectFromJson(String json) {
        Object object;
        try {
            object = jsonParseService(json, TextMessage.class);
            return (E) object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object = jsonParseService(json, FormatXmlImage.class);
            return (E) object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object = jsonParseService(json, FormatXmlMusic.class);
            return (E) object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object = jsonParseService(json, FormatXmlNews.class);
            return (E) object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object = jsonParseService(json, FormatXmlVideo.class);
            return (E) object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object = jsonParseService(json, FormatXmlVoice.class);
            return (E) object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, Object> getMap(String json) {
        HashMap<String, Object> map = new HashMap<>();
        Object object = getObjectFromJson(json);
        if (object instanceof TextMessage) {
            map.put(GlobalConstant.TEXT, object);
            return map;
        }
        if (object instanceof FormatXmlImage) {
            map.put(GlobalConstant.IMAGE, object);
            return map;
        }
        if (object instanceof FormatXmlMusic) {
            map.put(GlobalConstant.MUSIC, object);
        }
        if (object instanceof FormatXmlNews) {
            map.put(GlobalConstant.NEWS, object);
            return map;
        }
        if (object instanceof FormatXmlVideo) {
            map.put(GlobalConstant.VIDEO, object);
            return map;
        }
        if (object instanceof FormatXmlVoice) {
            map.put(GlobalConstant.VOICE, object);
            return map;
        }

        return map;
    }
}



